Your First GAN

Goal

In this notebook, you're going to create your first generative adversarial network (GAN) for this course! Specifically, you will build and train a GAN that can generate hand-written images of digits (0-9). You will be using PyTorch in this specialization, so if you're not familiar with this framework, you may find the PyTorch documentation useful. The hints will also often include links to relevant documentation.

Learning Objectives

  1. Build the generator and discriminator components of a GAN from scratch.
  2. Create generator and discriminator loss functions.
  3. Train your GAN and visualize the generated images.

Getting Started

You will begin by importing some useful packages and the dataset you will use to build and train your GAN. You are also provided with a visualizer function to help you investigate the images your GAN will create.

In [4]:
import torch
from torch import nn
from tqdm.auto import tqdm
from torchvision import transforms
from torchvision.datasets import MNIST # Training dataset
from torchvision.utils import make_grid
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
torch.manual_seed(0) # Set for testing purposes, please do not change!

def show_tensor_images(image_tensor, num_images=25, size=(1, 28, 28)):
    '''
    Function for visualizing images: Given a tensor of images, number of images, and
    size per image, plots and prints the images in a uniform grid.
    '''
    image_unflat = image_tensor.detach().cpu().view(-1, *size)
    image_grid = make_grid(image_unflat[:num_images], nrow=5)
    plt.imshow(image_grid.permute(1, 2, 0).squeeze())
    plt.show()

MNIST Dataset

The training images your discriminator will be using is from a dataset called MNIST. It contains 60,000 images of handwritten digits, from 0 to 9, like these:

MNIST Digits

You may notice that the images are quite pixelated -- this is because they are all only 28 x 28! The small size of its images makes MNIST ideal for simple training. Additionally, these images are also in black-and-white so only one dimension, or "color channel", is needed to represent them (more on this later in the course).

Tensor

You will represent the data using tensors. Tensors are a generalization of matrices: for example, a stack of three matrices with the amounts of red, green, and blue at different locations in a 64 x 64 pixel image is a tensor with the shape 3 x 64 x 64.

Tensors are easy to manipulate and supported by PyTorch, the machine learning library you will be using. Feel free to explore them more, but you can imagine these as multi-dimensional matrices or vectors!

Batches

While you could train your model after generating one image, it is extremely inefficient and leads to less stable training. In GANs, and in machine learning in general, you will process multiple images per training step. These are called batches.

This means that your generator will generate an entire batch of images and receive the discriminator's feedback on each before updating the model. The same goes for the discriminator, it will calculate its loss on the entire batch of generated images as well as on the reals before the model is updated.

Generator

The first step is to build the generator component.

You will start by creating a function to make a single layer/block for the generator's neural network. Each block should include a linear transformation to map to another shape, a batch normalization for stabilization, and finally a non-linear activation function (you use a ReLU here) so the output can be transformed in complex ways. You will learn more about activations and batch normalization later in the course.

In [5]:
# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: get_generator_block
def get_generator_block(input_dim, output_dim):
    '''
    Function for returning a block of the generator's neural network
    given input and output dimensions.
    Parameters:
        input_dim: the dimension of the input vector, a scalar
        output_dim: the dimension of the output vector, a scalar
    Returns:
        a generator neural network layer, with a linear transformation 
          followed by a batch normalization and then a relu activation
    '''
    return nn.Sequential(
        # Hint: Replace all of the "None" with the appropriate dimensions.
        # The documentation may be useful if you're less familiar with PyTorch:
        # https://pytorch.org/docs/stable/nn.html.
        #### START CODE HERE ####
        nn.Linear(input_dim, output_dim),
        nn.BatchNorm1d(output_dim),
        nn.ReLU(inplace=True),
        #### END CODE HERE ####
    )
In [6]:
# Verify the generator block function
def test_gen_block(in_features, out_features, num_test=1000):
    block = get_generator_block(in_features, out_features)

    # Check the three parts
    assert len(block) == 3
    assert type(block[0]) == nn.Linear
    assert type(block[1]) == nn.BatchNorm1d
    assert type(block[2]) == nn.ReLU
    
    # Check the output shape
    test_input = torch.randn(num_test, in_features)
    test_output = block(test_input)
    assert tuple(test_output.shape) == (num_test, out_features)
    assert test_output.std() > 0.55
    assert test_output.std() < 0.65

test_gen_block(25, 12)
test_gen_block(15, 28)
print("Success!")
Success!

Now you can build the generator class. It will take 3 values:

  • The noise vector dimension
  • The image dimension
  • The initial hidden dimension

Using these values, the generator will build a neural network with 5 layers/blocks. Beginning with the noise vector, the generator will apply non-linear transformations via the block function until the tensor is mapped to the size of the image to be outputted (the same size as the real images from MNIST). You will need to fill in the code for final layer since it is different than the others. The final layer does not need a normalization or activation function, but does need to be scaled with a sigmoid function.

Finally, you are given a forward pass function that takes in a noise vector and generates an image of the output dimension using your neural network.

Optional hints for Generator 1. The output size of the final linear transformation should be im_dim, but remember you need to scale the outputs between 0 and 1 using the sigmoid function. 2. [nn.Linear](https://pytorch.org/docs/master/generated/torch.nn.Linear.html) and [nn.Sigmoid](https://pytorch.org/docs/master/generated/torch.nn.Sigmoid.html) will be useful here.
In [7]:
# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: Generator
class Generator(nn.Module):
    '''
    Generator Class
    Values:
        z_dim: the dimension of the noise vector, a scalar
        im_dim: the dimension of the images, fitted for the dataset used, a scalar
          (MNIST images are 28 x 28 = 784 so that is your default)
        hidden_dim: the inner dimension, a scalar
    '''
    def __init__(self, z_dim=10, im_dim=784, hidden_dim=128):
        super(Generator, self).__init__()
        # Build the neural network
        self.gen = nn.Sequential(
            get_generator_block(z_dim, hidden_dim),
            get_generator_block(hidden_dim, hidden_dim * 2),
            get_generator_block(hidden_dim * 2, hidden_dim * 4),
            get_generator_block(hidden_dim * 4, hidden_dim * 8),
            # There is a dropdown with hints if you need them! 
            #### START CODE HERE ####
            nn.Linear(hidden_dim * 8 , im_dim),
            nn.Sigmoid()
            #### END CODE HERE ####
        )
    def forward(self, noise):
        '''
        Function for completing a forward pass of the generator: Given a noise tensor, 
        returns generated images.
        Parameters:
            noise: a noise tensor with dimensions (n_samples, z_dim)
        '''
        return self.gen(noise)
    
    # Needed for grading
    def get_gen(self):
        '''
        Returns:
            the sequential model
        '''
        return self.gen
In [8]:
# Verify the generator class
def test_generator(z_dim, im_dim, hidden_dim, num_test=10000):
    gen = Generator(z_dim, im_dim, hidden_dim).get_gen()
    print(gen)
    
    # Check there are six modules in the sequential part
    assert len(gen) == 6
    test_input = torch.randn(num_test, z_dim)
    test_output = gen(test_input)

    # Check that the output shape is correct
    assert tuple(test_output.shape) == (num_test, im_dim)
    assert test_output.max() < 1, "Make sure to use a sigmoid"
    assert test_output.min() > 0, "Make sure to use a sigmoid"
    assert test_output.std() > 0.05, "Don't use batchnorm here"
    assert test_output.std() < 0.15, "Don't use batchnorm here"

test_generator(5, 10, 20)
test_generator(20, 8, 24)
print("Success!")
Sequential(
  (0): Sequential(
    (0): Linear(in_features=5, out_features=20, bias=True)
    (1): BatchNorm1d(20, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU(inplace=True)
  )
  (1): Sequential(
    (0): Linear(in_features=20, out_features=40, bias=True)
    (1): BatchNorm1d(40, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU(inplace=True)
  )
  (2): Sequential(
    (0): Linear(in_features=40, out_features=80, bias=True)
    (1): BatchNorm1d(80, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU(inplace=True)
  )
  (3): Sequential(
    (0): Linear(in_features=80, out_features=160, bias=True)
    (1): BatchNorm1d(160, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU(inplace=True)
  )
  (4): Linear(in_features=160, out_features=10, bias=True)
  (5): Sigmoid()
)
Sequential(
  (0): Sequential(
    (0): Linear(in_features=20, out_features=24, bias=True)
    (1): BatchNorm1d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU(inplace=True)
  )
  (1): Sequential(
    (0): Linear(in_features=24, out_features=48, bias=True)
    (1): BatchNorm1d(48, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU(inplace=True)
  )
  (2): Sequential(
    (0): Linear(in_features=48, out_features=96, bias=True)
    (1): BatchNorm1d(96, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU(inplace=True)
  )
  (3): Sequential(
    (0): Linear(in_features=96, out_features=192, bias=True)
    (1): BatchNorm1d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU(inplace=True)
  )
  (4): Linear(in_features=192, out_features=8, bias=True)
  (5): Sigmoid()
)
Success!

Noise

To be able to use your generator, you will need to be able to create noise vectors. The noise vector z has the important role of making sure the images generated from the same class don't all look the same -- think of it as a random seed. You will generate it randomly using PyTorch by sampling random numbers from the normal distribution. Since multiple images will be processed per pass, you will generate all the noise vectors at once.

Note that whenever you create a new tensor using torch.ones, torch.zeros, or torch.randn, you either need to create it on the target device, e.g. torch.ones(3, 3, device=device), or move it onto the target device using torch.ones(3, 3).to(device). You do not need to do this if you're creating a tensor by manipulating another tensor or by using a variation that defaults the device to the input, such as torch.ones_like. In general, use torch.ones_like and torch.zeros_like instead of torch.ones or torch.zeros where possible.

Optional hint for get_noise 1. You will probably find [torch.randn](https://pytorch.org/docs/master/generated/torch.randn.html) useful here.
In [9]:
# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: get_noise
def get_noise(n_samples, z_dim, device='cpu'):
    '''
    Function for creating noise vectors: Given the dimensions (n_samples, z_dim),
    creates a tensor of that shape filled with random numbers from the normal distribution.
    Parameters:
        n_samples: the number of samples to generate, a scalar
        z_dim: the dimension of the noise vector, a scalar
        device: the device type
    '''
    # NOTE: To use this on GPU with device='cuda', make sure to pass the device 
    # argument to the function you use to generate the noise.
    #### START CODE HERE ####
    return torch.randn(n_samples,z_dim ,device = device)
    #### END CODE HERE ####
In [10]:
# Verify the noise vector function
def test_get_noise(n_samples, z_dim, device='cpu'):
    noise = get_noise(n_samples, z_dim, device)
    
    # Make sure a normal distribution was used
    assert tuple(noise.shape) == (n_samples, z_dim)
    assert torch.abs(noise.std() - torch.tensor(1.0)) < 0.01
    assert str(noise.device).startswith(device)

test_get_noise(1000, 100, 'cpu')
if torch.cuda.is_available():
    test_get_noise(1000, 32, 'cuda')
print("Success!")
Success!

Discriminator

The second component that you need to construct is the discriminator. As with the generator component, you will start by creating a function that builds a neural network block for the discriminator.

Note: You use leaky ReLUs to prevent the "dying ReLU" problem, which refers to the phenomenon where the parameters stop changing due to consistently negative values passed to a ReLU, which result in a zero gradient. You will learn more about this in the following lectures!

REctified Linear Unit (ReLU) Leaky ReLU
In [11]:
# UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: get_discriminator_block
def get_discriminator_block(input_dim, output_dim):
    '''
    Discriminator Block
    Function for returning a neural network of the discriminator given input and output dimensions.
    Parameters:
        input_dim: the dimension of the input vector, a scalar
        output_dim: the dimension of the output vector, a scalar
    Returns:
        a discriminator neural network layer, with a linear transformation 
          followed by an nn.LeakyReLU activation with negative slope of 0.2 
          (https://pytorch.org/docs/master/generated/torch.nn.LeakyReLU.html)
    '''
    return nn.Sequential(
        #### START CODE HERE ####
        nn.Linear(input_dim ,output_dim ),
        nn.LeakyReLU(0.2, inplace=True)

        #### END CODE HERE ####
    )
In [12]:
# Verify the discriminator block function
def test_disc_block(in_features, out_features, num_test=10000):
    block = get_discriminator_block(in_features, out_features)
    print(block)

    # Check there are two parts
    assert len(block) == 2
    test_input = torch.randn(num_test, in_features)
    test_output = block(test_input)

    # Check that the shape is right
    assert tuple(test_output.shape) == (num_test, out_features)
    
    # Check that the LeakyReLU slope is about 0.2
    assert -test_output.min() / test_output.max() > 0.1
    assert -test_output.min() / test_output.max() < 0.3
    assert test_output.std() > 0.3
    assert test_output.std() < 0.5

test_disc_block(25, 12)
test_disc_block(15, 28)
print("Success!")
Sequential(
  (0): Linear(in_features=25, out_features=12, bias=True)
  (1): LeakyReLU(negative_slope=0.2, inplace=True)
)
Sequential(
  (0): Linear(in_features=15, out_features=28, bias=True)
  (1): LeakyReLU(negative_slope=0.2, inplace=True)
)
Success!

Now you can use these blocks to make a discriminator! The discriminator class holds 2 values:

  • The image dimension
  • The hidden dimension

The discriminator will build a neural network with 4 layers. It will start with the image tensor and transform it until it returns a single number (1-dimension tensor) output. This output classifies whether an image is fake or real. Note that you do not need a sigmoid after the output layer since it is included in the loss function. Finally, to use your discrimator's neural network you are given a forward pass function that takes in an image tensor to be classified.

In [13]:
# UNQ_C5 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: Discriminator
class Discriminator(nn.Module):
    '''
    Discriminator Class
    Values:
        im_dim: the dimension of the images, fitted for the dataset used, a scalar
            (MNIST images are 28x28 = 784 so that is your default)
        hidden_dim: the inner dimension, a scalar
    '''
    def __init__(self, im_dim=784, hidden_dim=128):
        super(Discriminator, self).__init__()
        self.disc = nn.Sequential(
            get_discriminator_block(im_dim, hidden_dim * 4),
            get_discriminator_block(hidden_dim * 4, hidden_dim * 2),
            get_discriminator_block(hidden_dim * 2, hidden_dim),
            # Hint: You want to transform the final output into a single value,
            #       so add one more linear map.
            #### START CODE HERE ####
            nn.Linear( hidden_dim , 1)

            #### END CODE HERE ####
        )

    def forward(self, image):
        '''
        Function for completing a forward pass of the discriminator: Given an image tensor, 
        returns a 1-dimension tensor representing fake/real.
        Parameters:
            image: a flattened image tensor with dimension (im_dim)
        '''
        return self.disc(image)
    
    # Needed for grading
    def get_disc(self):
        '''
        Returns:
            the sequential model
        '''
        return self.disc
In [14]:
# Verify the discriminator class
def test_discriminator(z_dim, hidden_dim, num_test=100):
    
    disc = Discriminator(z_dim, hidden_dim).get_disc()
    print(disc)
    # Check there are three parts
    assert len(disc) == 4

    # Check the linear layer is correct
    test_input = torch.randn(num_test, z_dim)
    test_output = disc(test_input)
    assert tuple(test_output.shape) == (num_test, 1)
    
    # Make sure there's no sigmoid
    assert test_input.max() > 1
    assert test_input.min() < -1

test_discriminator(5, 10)
test_discriminator(20, 8)
print("Success!")
Sequential(
  (0): Sequential(
    (0): Linear(in_features=5, out_features=40, bias=True)
    (1): LeakyReLU(negative_slope=0.2, inplace=True)
  )
  (1): Sequential(
    (0): Linear(in_features=40, out_features=20, bias=True)
    (1): LeakyReLU(negative_slope=0.2, inplace=True)
  )
  (2): Sequential(
    (0): Linear(in_features=20, out_features=10, bias=True)
    (1): LeakyReLU(negative_slope=0.2, inplace=True)
  )
  (3): Linear(in_features=10, out_features=1, bias=True)
)
Sequential(
  (0): Sequential(
    (0): Linear(in_features=20, out_features=32, bias=True)
    (1): LeakyReLU(negative_slope=0.2, inplace=True)
  )
  (1): Sequential(
    (0): Linear(in_features=32, out_features=16, bias=True)
    (1): LeakyReLU(negative_slope=0.2, inplace=True)
  )
  (2): Sequential(
    (0): Linear(in_features=16, out_features=8, bias=True)
    (1): LeakyReLU(negative_slope=0.2, inplace=True)
  )
  (3): Linear(in_features=8, out_features=1, bias=True)
)
Success!

Training

Now you can put it all together! First, you will set your parameters:

  • criterion: the loss function
  • n_epochs: the number of times you iterate through the entire dataset when training
  • z_dim: the dimension of the noise vector
  • display_step: how often to display/visualize the images
  • batch_size: the number of images per forward/backward pass
  • lr: the learning rate
  • device: the device type, here using a GPU (which runs CUDA), not CPU

Next, you will load the MNIST dataset as tensors using a dataloader.

In [15]:
# Set your parameters
criterion = nn.BCEWithLogitsLoss()
n_epochs = 200
z_dim = 64
display_step = 500
batch_size = 128
lr = 0.00001

# Load MNIST dataset as tensors
dataloader = DataLoader(
    MNIST('.', download=False, transform=transforms.ToTensor()),
    batch_size=batch_size,
    shuffle=True)

### DO NOT EDIT ###
device = 'cuda'

Now, you can initialize your generator, discriminator, and optimizers. Note that each optimizer only takes the parameters of one particular model, since we want each optimizer to optimize only one of the models.

In [16]:
gen = Generator(z_dim).to(device)
gen_opt = torch.optim.Adam(gen.parameters(), lr=lr)
disc = Discriminator().to(device) 
disc_opt = torch.optim.Adam(disc.parameters(), lr=lr)

Before you train your GAN, you will need to create functions to calculate the discriminator's loss and the generator's loss. This is how the discriminator and generator will know how they are doing and improve themselves. Since the generator is needed when calculating the discriminator's loss, you will need to call .detach() on the generator result to ensure that only the discriminator is updated!

Remember that you have already defined a loss function earlier (criterion) and you are encouraged to use torch.ones_like and torch.zeros_like instead of torch.ones or torch.zeros. If you use torch.ones or torch.zeros, you'll need to pass device=device to them.

In [17]:
# UNQ_C6 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: get_disc_loss
def get_disc_loss(gen, disc, criterion, real, num_images, z_dim, device):
    '''
    Return the loss of the discriminator given inputs.
    Parameters:
        gen: the generator model, which returns an image given z-dimensional noise
        disc: the discriminator model, which returns a single-dimensional prediction of real/fake
        criterion: the loss function, which should be used to compare 
               the discriminator's predictions to the ground truth reality of the images 
               (e.g. fake = 0, real = 1)
        real: a batch of real images
        num_images: the number of images the generator should produce, 
                which is also the length of the real images
        z_dim: the dimension of the noise vector, a scalar
        device: the device type
    Returns:
        disc_loss: a torch scalar loss value for the current batch
    '''
    #     These are the steps you will need to complete:
    #       1) Create noise vectors and generate a batch (num_images) of fake images. 
    #            Make sure to pass the device argument to the noise.
    #       2) Get the discriminator's prediction of the fake image 
    #            and calculate the loss. Don't forget to detach the generator!
    #            (Remember the loss function you set earlier -- criterion. You need a 
    #            'ground truth' tensor in order to calculate the loss. 
    #            For example, a ground truth tensor for a fake image is all zeros.)
    #       3) Get the discriminator's prediction of the real image and calculate the loss.
    #       4) Calculate the discriminator's loss by averaging the real and fake loss
    #            and set it to disc_loss.
    #     Note: Please do not use concatenation in your solution. The tests are being updated to 
    #           support this, but for now, average the two losses as described in step (4).
    #     *Important*: You should NOT write your own loss function here - use criterion(pred, true)!
    #### START CODE HERE ####
    fake_noise = get_noise(num_images, z_dim, device=device)
    fake = gen(fake_noise)
    disc_fake_pred = disc(fake.detach())
    disc_fake_loss = criterion(disc_fake_pred, torch.zeros_like(disc_fake_pred))
    disc_real_pred = disc(real)
    disc_real_loss = criterion(disc_real_pred, torch.ones_like(disc_real_pred))
    disc_loss = (disc_fake_loss + disc_real_loss) / 2
    #### END CODE HERE ####
    return disc_loss
In [18]:
def test_disc_reasonable(num_images=10):
    # Don't use explicit casts to cuda - use the device argument
    import inspect, re
    lines = inspect.getsource(get_disc_loss)
    assert (re.search(r"to\(.cuda.\)", lines)) is None
    assert (re.search(r"\.cuda\(\)", lines)) is None
    
    z_dim = 64
    gen = torch.zeros_like
    disc = lambda x: x.mean(1)[:, None]
    criterion = torch.mul # Multiply
    real = torch.ones(num_images, z_dim)
    disc_loss = get_disc_loss(gen, disc, criterion, real, num_images, z_dim, 'cpu')
    assert torch.all(torch.abs(disc_loss.mean() - 0.5) < 1e-5)
    
    gen = torch.ones_like
    criterion = torch.mul # Multiply
    real = torch.zeros(num_images, z_dim)
    assert torch.all(torch.abs(get_disc_loss(gen, disc, criterion, real, num_images, z_dim, 'cpu')) < 1e-5)
    
    gen = lambda x: torch.ones(num_images, 10)
    disc = lambda x: x.mean(1)[:, None] + 10
    criterion = torch.mul # Multiply
    real = torch.zeros(num_images, 10)
    assert torch.all(torch.abs(get_disc_loss(gen, disc, criterion, real, num_images, z_dim, 'cpu').mean() - 5) < 1e-5)

    gen = torch.ones_like
    disc = nn.Linear(64, 1, bias=False)
    real = torch.ones(num_images, 64) * 0.5
    disc.weight.data = torch.ones_like(disc.weight.data) * 0.5
    disc_opt = torch.optim.Adam(disc.parameters(), lr=lr)
    criterion = lambda x, y: torch.sum(x) + torch.sum(y)
    disc_loss = get_disc_loss(gen, disc, criterion, real, num_images, z_dim, 'cpu').mean()
    disc_loss.backward()
    assert torch.isclose(torch.abs(disc.weight.grad.mean() - 11.25), torch.tensor(3.75))
    
def test_disc_loss(max_tests = 10):
    z_dim = 64
    gen = Generator(z_dim).to(device)
    gen_opt = torch.optim.Adam(gen.parameters(), lr=lr)
    disc = Discriminator().to(device) 
    disc_opt = torch.optim.Adam(disc.parameters(), lr=lr)
    num_steps = 0
    for real, _ in dataloader:
        cur_batch_size = len(real)
        real = real.view(cur_batch_size, -1).to(device)

        ### Update discriminator ###
        # Zero out the gradient before backpropagation
        disc_opt.zero_grad()

        # Calculate discriminator loss
        disc_loss = get_disc_loss(gen, disc, criterion, real, cur_batch_size, z_dim, device)
        assert (disc_loss - 0.68).abs() < 0.05

        # Update gradients
        disc_loss.backward(retain_graph=True)

        # Check that they detached correctly
        assert gen.gen[0][0].weight.grad is None

        # Update optimizer
        old_weight = disc.disc[0][0].weight.data.clone()
        disc_opt.step()
        new_weight = disc.disc[0][0].weight.data
        
        # Check that some discriminator weights changed
        assert not torch.all(torch.eq(old_weight, new_weight))
        num_steps += 1
        if num_steps >= max_tests:
            break

test_disc_reasonable()
test_disc_loss()
print("Success!")
Success!
In [19]:
# UNQ_C7 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: get_gen_loss
def get_gen_loss(gen, disc, criterion, num_images, z_dim, device):
    '''
    Return the loss of the generator given inputs.
    Parameters:
        gen: the generator model, which returns an image given z-dimensional noise
        disc: the discriminator model, which returns a single-dimensional prediction of real/fake
        criterion: the loss function, which should be used to compare 
               the discriminator's predictions to the ground truth reality of the images 
               (e.g. fake = 0, real = 1)
        num_images: the number of images the generator should produce, 
                which is also the length of the real images
        z_dim: the dimension of the noise vector, a scalar
        device: the device type
    Returns:
        gen_loss: a torch scalar loss value for the current batch
    '''
    #     These are the steps you will need to complete:
    #       1) Create noise vectors and generate a batch of fake images. 
    #           Remember to pass the device argument to the get_noise function.
    #       2) Get the discriminator's prediction of the fake image.
    #       3) Calculate the generator's loss. Remember the generator wants
    #          the discriminator to think that its fake images are real
    #     *Important*: You should NOT write your own loss function here - use criterion(pred, true)!

    #### START CODE HERE ####
    fake_noise = get_noise(num_images, z_dim, device=device)
    fake = gen(fake_noise)
    disc_fake_pred = disc(fake)
    gen_loss = criterion(disc_fake_pred, torch.ones_like(disc_fake_pred))
    #### END CODE HERE ####
    return gen_loss
In [20]:
def test_gen_reasonable(num_images=10):
    # Don't use explicit casts to cuda - use the device argument
    import inspect, re
    lines = inspect.getsource(get_gen_loss)
    assert (re.search(r"to\(.cuda.\)", lines)) is None
    assert (re.search(r"\.cuda\(\)", lines)) is None
    
    z_dim = 64
    gen = torch.zeros_like
    disc = nn.Identity()
    criterion = torch.mul # Multiply
    gen_loss_tensor = get_gen_loss(gen, disc, criterion, num_images, z_dim, 'cpu')
    assert torch.all(torch.abs(gen_loss_tensor) < 1e-5)
    #Verify shape. Related to gen_noise parametrization
    assert tuple(gen_loss_tensor.shape) == (num_images, z_dim)

    gen = torch.ones_like
    disc = nn.Identity()
    criterion = torch.mul # Multiply
    real = torch.zeros(num_images, 1)
    gen_loss_tensor = get_gen_loss(gen, disc, criterion, num_images, z_dim, 'cpu')
    assert torch.all(torch.abs(gen_loss_tensor - 1) < 1e-5)
    #Verify shape. Related to gen_noise parametrization
    assert tuple(gen_loss_tensor.shape) == (num_images, z_dim)
    

def test_gen_loss(num_images):
    z_dim = 64
    gen = Generator(z_dim).to(device)
    gen_opt = torch.optim.Adam(gen.parameters(), lr=lr)
    disc = Discriminator().to(device) 
    disc_opt = torch.optim.Adam(disc.parameters(), lr=lr)
    
    gen_loss = get_gen_loss(gen, disc, criterion, num_images, z_dim, device)
    
    # Check that the loss is reasonable
    assert (gen_loss - 0.7).abs() < 0.1
    gen_loss.backward()
    old_weight = gen.gen[0][0].weight.clone()
    gen_opt.step()
    new_weight = gen.gen[0][0].weight
    assert not torch.all(torch.eq(old_weight, new_weight))


test_gen_reasonable(10)
test_gen_loss(18)
print("Success!")
Success!

Finally, you can put everything together! For each epoch, you will process the entire dataset in batches. For every batch, you will need to update the discriminator and generator using their loss. Batches are sets of images that will be predicted on before the loss functions are calculated (instead of calculating the loss function after each image). Note that you may see a loss to be greater than 1, this is okay since binary cross entropy loss can be any positive number for a sufficiently confident wrong guess.

It’s also often the case that the discriminator will outperform the generator, especially at the start, because its job is easier. It's important that neither one gets too good (that is, near-perfect accuracy), which would cause the entire model to stop learning. Balancing the two models is actually remarkably hard to do in a standard GAN and something you will see more of in later lectures and assignments.

After you've submitted a working version with the original architecture, feel free to play around with the architecture if you want to see how different architectural choices can lead to better or worse GANs. For example, consider changing the size of the hidden dimension, or making the networks shallower or deeper by changing the number of layers.

But remember, don’t expect anything spectacular: this is only the first lesson. The results will get better with later lessons as you learn methods to help keep your generator and discriminator at similar levels.

You should roughly expect to see this progression. On a GPU, this should take about 15 seconds per 500 steps, on average, while on CPU it will take roughly 1.5 minutes: MNIST Digits

In [ ]:
# UNQ_C8 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
# GRADED FUNCTION: 

cur_step = 0
mean_generator_loss = 0
mean_discriminator_loss = 0
test_generator = True # Whether the generator should be tested
gen_loss = False
for epoch in range(n_epochs):
  
    # Dataloader returns the batches
    for real, _ in tqdm(dataloader):
        cur_batch_size = len(real)

        # Flatten the batch of real images from the dataset
        real = real.view(cur_batch_size, -1).to(device)

        ### Update discriminator ###
        # Zero out the gradients before backpropagation
        disc_opt.zero_grad()

        # Calculate discriminator loss
        disc_loss = get_disc_loss(gen, disc, criterion, real, cur_batch_size, z_dim, device)

        # Update gradients
        disc_loss.backward(retain_graph=True)

        # Update optimizer
        disc_opt.step()

        # For testing purposes, to keep track of the generator weights
        if test_generator:
            old_generator_weights = gen.gen[0][0].weight.detach().clone()

        ### Update generator ###
        #     Hint: This code will look a lot like the discriminator updates!
        #     These are the steps you will need to complete:
        #       1) Zero out the gradients.
        #       2) Calculate the generator loss, assigning it to gen_loss.
        #       3) Backprop through the generator: update the gradients and optimizer.
        #### START CODE HERE ####
        gen_opt.zero_grad()
        gen_loss = get_gen_loss(gen, disc, criterion, cur_batch_size, z_dim, device)
        gen_loss.backward()
        gen_opt.step()
        #### END CODE HERE ####

        # For testing purposes, to check that your code changes the generator weights
        if test_generator:
            assert torch.any(gen.gen[0][0].weight.detach().clone() != old_generator_weights)

        # Keep track of the average discriminator loss
        mean_discriminator_loss += disc_loss.item() / display_step

        # Keep track of the average generator loss
        mean_generator_loss += gen_loss.item() / display_step

        ### Visualization code ###
        if cur_step % display_step == 0 and cur_step > 0:
            print(f"Step {cur_step}: Generator loss: {mean_generator_loss}, discriminator loss: {mean_discriminator_loss}")
            fake_noise = get_noise(cur_batch_size, z_dim, device=device)
            fake = gen(fake_noise)
            show_tensor_images(fake)
            show_tensor_images(real)
            mean_generator_loss = 0
            mean_discriminator_loss = 0
        cur_step += 1

Step 500: Generator loss: 1.414591051459312, discriminator loss: 0.41323195016384123

Step 1000: Generator loss: 1.7672956192493452, discriminator loss: 0.2761800294518474

Step 1500: Generator loss: 2.0682682147026052, discriminator loss: 0.15814117138087758

Step 2000: Generator loss: 1.6611715803146352, discriminator loss: 0.22914810961484924

Step 2500: Generator loss: 1.6687853374481203, discriminator loss: 0.2070558182895184

Step 3000: Generator loss: 1.9007605841159825, discriminator loss: 0.17540681406855593

Step 3500: Generator loss: 2.248719641208649, discriminator loss: 0.14857690735161302

Step 4000: Generator loss: 2.713124620437621, discriminator loss: 0.11242729128897191

Step 4500: Generator loss: 3.0910654268264808, discriminator loss: 0.08523133224248876

Step 5000: Generator loss: 3.530671156406403, discriminator loss: 0.0649003976583481

Step 5500: Generator loss: 3.8935977578163103, discriminator loss: 0.05395714708417657

Step 6000: Generator loss: 3.9744777388572694, discriminator loss: 0.05144385391846296

Step 6500: Generator loss: 4.20372106552124, discriminator loss: 0.04369043921306728

Step 7000: Generator loss: 4.255566555976868, discriminator loss: 0.051193204820156026

Step 7500: Generator loss: 4.064803722858427, discriminator loss: 0.04973368621617554


Step 8000: Generator loss: 4.280081794261929, discriminator loss: 0.04577760566398505

Step 8500: Generator loss: 4.261904405593871, discriminator loss: 0.05254924758896232

Step 9000: Generator loss: 4.354080021858216, discriminator loss: 0.05089422895014287

Step 9500: Generator loss: 4.282235364437101, discriminator loss: 0.05567146166786555

Step 10000: Generator loss: 4.251584539413447, discriminator loss: 0.05067119330167766

Step 10500: Generator loss: 4.4452417416572585, discriminator loss: 0.051653804827481484

Step 11000: Generator loss: 4.296972921371457, discriminator loss: 0.061620019655674714

Step 11500: Generator loss: 4.317264967918396, discriminator loss: 0.07153821654617788

Step 12000: Generator loss: 4.496293818950648, discriminator loss: 0.06634571659192441

Step 12500: Generator loss: 4.303576992988584, discriminator loss: 0.0715679063163698

Step 13000: Generator loss: 4.040393764019013, discriminator loss: 0.08435110989958054

Step 13500: Generator loss: 4.255043917655944, discriminator loss: 0.07329927647113806

Step 14000: Generator loss: 4.011653150558476, discriminator loss: 0.09164363686740395

Step 14500: Generator loss: 4.007131385326385, discriminator loss: 0.09430022063851352

Step 15000: Generator loss: 3.964840143203735, discriminator loss: 0.09309413264691824


Step 15500: Generator loss: 3.903413704872132, discriminator loss: 0.09717361004650589

Step 16000: Generator loss: 3.766596974372865, discriminator loss: 0.1149802436009049

Step 16500: Generator loss: 3.6666146206855763, discriminator loss: 0.12258071427047258

Step 17000: Generator loss: 3.592471503257754, discriminator loss: 0.12137402136623857

Step 17500: Generator loss: 3.5806128873825096, discriminator loss: 0.11940311549603948

Step 18000: Generator loss: 3.563631630897521, discriminator loss: 0.12738265808671703

Step 18500: Generator loss: 3.550328680515288, discriminator loss: 0.13707059942185879

Step 19000: Generator loss: 3.363407487392426, discriminator loss: 0.14108470728993427

Step 19500: Generator loss: 3.3017451701164235, discriminator loss: 0.14319682011008267

Step 20000: Generator loss: 3.2483152217864992, discriminator loss: 0.1437131165713071

Step 20500: Generator loss: 3.3395065879821777, discriminator loss: 0.14508688305318368

Step 21000: Generator loss: 3.1686455979347214, discriminator loss: 0.17384615905582912

Step 21500: Generator loss: 3.0553576889038077, discriminator loss: 0.1753911269754171

Step 22000: Generator loss: 3.010243177890778, discriminator loss: 0.1727208175808191

Step 22500: Generator loss: 2.899782027244569, discriminator loss: 0.18122482939064505


Step 23000: Generator loss: 2.994066712379456, discriminator loss: 0.17776190982758994

Step 23500: Generator loss: 3.033061884880065, discriminator loss: 0.17449328657984742

Step 24000: Generator loss: 3.008525679588316, discriminator loss: 0.16904934832453725

Step 24500: Generator loss: 2.9192654857635496, discriminator loss: 0.18555045276880272

Step 25000: Generator loss: 2.863173091411587, discriminator loss: 0.18326669819653021

Step 25500: Generator loss: 2.7508806233406062, discriminator loss: 0.20690793921053421

Step 26000: Generator loss: 2.735884463310245, discriminator loss: 0.1985298127233983

Step 26500: Generator loss: 2.824126577854156, discriminator loss: 0.18482244293391692

Step 27000: Generator loss: 2.8577418198585547, discriminator loss: 0.18728231149911875

Step 27500: Generator loss: 2.692674867630009, discriminator loss: 0.21357738113403327

Step 28000: Generator loss: 2.585279714107513, discriminator loss: 0.2140989062935113

Step 28500: Generator loss: 2.7677832708358765, discriminator loss: 0.19556621490418902

Step 29000: Generator loss: 2.65196467924118, discriminator loss: 0.20999538922309885

Step 29500: Generator loss: 2.6439098277091957, discriminator loss: 0.22176857890188684

Step 30000: Generator loss: 2.43300956916809, discriminator loss: 0.2525565581619741


Step 30500: Generator loss: 2.6790854215621946, discriminator loss: 0.19838270379602885

Step 31000: Generator loss: 2.6116938495635984, discriminator loss: 0.2150889437198636

Step 31500: Generator loss: 2.638289703845977, discriminator loss: 0.20621153107285495

Step 32000: Generator loss: 2.578825434684751, discriminator loss: 0.23670587529242043

Step 32500: Generator loss: 2.563841169834138, discriminator loss: 0.22749185749888448

Step 33000: Generator loss: 2.4622486438751237, discriminator loss: 0.25586656641960154

Step 33500: Generator loss: 2.3509061410427106, discriminator loss: 0.259535434871912

Step 34000: Generator loss: 2.3243594264984115, discriminator loss: 0.26656437346339223

Step 34500: Generator loss: 2.3080303344726563, discriminator loss: 0.26498322853446016

Step 35000: Generator loss: 2.545761528491975, discriminator loss: 0.2241789633929728

Step 35500: Generator loss: 2.551966063976288, discriminator loss: 0.2370608358085153

Step 36000: Generator loss: 2.2197521972656262, discriminator loss: 0.28445926663279525

Step 36500: Generator loss: 2.3590646817684164, discriminator loss: 0.24869311526417745

Step 37000: Generator loss: 2.1685319528579696, discriminator loss: 0.2897499275803565

Step 37500: Generator loss: 2.255173615694047, discriminator loss: 0.2669391385018827


Step 38000: Generator loss: 2.1153760817050915, discriminator loss: 0.31056240421533593

Step 38500: Generator loss: 2.3044458277225472, discriminator loss: 0.26166901019215577

Step 39000: Generator loss: 2.3033152637481678, discriminator loss: 0.2636790253221991

Step 39500: Generator loss: 2.246301263809204, discriminator loss: 0.27470021539926515

Step 40000: Generator loss: 2.1865415573120095, discriminator loss: 0.2827800400555135

Step 40500: Generator loss: 2.0067020909786217, discriminator loss: 0.3270862747728826

Step 41000: Generator loss: 1.9879608242511753, discriminator loss: 0.31625015890598285

Step 41500: Generator loss: 2.071404409408569, discriminator loss: 0.29366648283600805

Step 42000: Generator loss: 2.1191696727275837, discriminator loss: 0.29127053877711284

Step 42500: Generator loss: 2.087877621650693, discriminator loss: 0.29749346008896815

Step 43000: Generator loss: 1.9634721078872686, discriminator loss: 0.3234990461170674

Step 43500: Generator loss: 1.9372532906532285, discriminator loss: 0.3175244944989683

Step 44000: Generator loss: 1.9656029644012438, discriminator loss: 0.32119264802336683

Step 44500: Generator loss: 2.072222431898117, discriminator loss: 0.2970707264542579

Step 45000: Generator loss: 1.9940351691246023, discriminator loss: 0.3154555871188639


Step 45500: Generator loss: 1.8655109546184543, discriminator loss: 0.33527099141478567

Step 46000: Generator loss: 1.9503532567024247, discriminator loss: 0.3164614307284356

Step 46500: Generator loss: 1.89534712934494, discriminator loss: 0.3324288395047188

Step 47000: Generator loss: 2.0586209299564366, discriminator loss: 0.29411718010902393

Step 47500: Generator loss: 1.9573540232181539, discriminator loss: 0.3245522065460681

Step 48000: Generator loss: 1.9229476244449608, discriminator loss: 0.32765013414621347

Step 48500: Generator loss: 1.857226760149003, discriminator loss: 0.33441133078932767

Step 49000: Generator loss: 1.923412265062333, discriminator loss: 0.31972164702415445

Step 49500: Generator loss: 1.8521912827491758, discriminator loss: 0.3372656556367874

Step 50000: Generator loss: 1.7686854472160347, discriminator loss: 0.3426838803291324

Step 50500: Generator loss: 1.813898238420487, discriminator loss: 0.3412780897915363

Step 51000: Generator loss: 1.7753228342533105, discriminator loss: 0.3491246294975279

Step 51500: Generator loss: 1.8715804948806745, discriminator loss: 0.3356228136718273

Step 52000: Generator loss: 1.8011659173965446, discriminator loss: 0.3453076400458811

Step 52500: Generator loss: 1.8576348240375533, discriminator loss: 0.3281088925302028


Step 53000: Generator loss: 1.8277766110897058, discriminator loss: 0.33653273773193393

Step 53500: Generator loss: 1.8604257452487933, discriminator loss: 0.3312029844522474

Step 54000: Generator loss: 1.8849042150974258, discriminator loss: 0.33056195172667474

Step 54500: Generator loss: 1.7741457462310795, discriminator loss: 0.3574498823285103

Step 55000: Generator loss: 1.8921798791885385, discriminator loss: 0.3289932663142685

Step 55500: Generator loss: 1.7754224867820751, discriminator loss: 0.3494415051937106

Step 56000: Generator loss: 1.7728765037059793, discriminator loss: 0.3483636027574536

Step 56500: Generator loss: 1.668208665609361, discriminator loss: 0.38270719164609884

Step 57000: Generator loss: 1.7156948997974415, discriminator loss: 0.3541068039536474

Step 57500: Generator loss: 1.8020048978328704, discriminator loss: 0.34069590789079646

Step 58000: Generator loss: 1.754722489118577, discriminator loss: 0.35710474395751907

Step 58500: Generator loss: 1.6458043625354755, discriminator loss: 0.3723387677967545

Step 59000: Generator loss: 1.6384052441120127, discriminator loss: 0.3824661796092987

Step 59500: Generator loss: 1.63179318499565, discriminator loss: 0.37922817587852475

Step 60000: Generator loss: 1.6635293481349958, discriminator loss: 0.37092128640413324

Step 60500: Generator loss: 1.646180191278459, discriminator loss: 0.3870926933884622


Step 61000: Generator loss: 1.610459934234619, discriminator loss: 0.38707770061492913

Step 61500: Generator loss: 1.6270038626194003, discriminator loss: 0.38491352325677863

Step 62000: Generator loss: 1.683329757213592, discriminator loss: 0.36609400618076304

Step 62500: Generator loss: 1.6344461123943324, discriminator loss: 0.3790110731124883

In [ ]: